package com.chinasoft.carservice.service.impl;

import com.chinasoft.carservice.mapper.CarMpper;
import com.chinasoft.carservice.service.CarService;
import com.chinasoft.feignclient.client.CarWithUserClient;
import com.chinasoft.feignclient.client.RentalClient;
import com.chinasoft.feignclient.client.UserClient;
import com.chinasoft.ms.dto.*;
import com.chinasoft.ms.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RefreshScope
@Service
//@AllArgsConstructor
public class CarServiceImpl implements CarService {

    @Value("${car.rental.status.rented:0}")  // 从配置中心获取租用状态标识
    private String rentedStatus;

    @Value("${car.logging.enabled:false}")  // 是否启用调试日志
    private boolean loggingEnabled;



    @Autowired
    CarMpper carMapper;
    @Autowired
    UserClient userClient;
    @Autowired
    RentalClient rentalClient;

    @Autowired
    CarWithUserClient carWithUserClient;

    @Override
    public boolean updateStatus(Long carId, String s) {
        return carMapper.updateStatus(carId, s);
    }

    @Override
    public CarDTO selectCarById(Long id) {
        CarDTO carDTO = convertToCarDTO(carMapper.selectById(id));
        return carDTO;
    }


    @Override
    public List<CarDTO> searchCarDTOs(CarDTO queryDto) {
        // 转换为实体查询条件
        Car query = convertToCar(queryDto);

        // 查询数据库
        List<Car> cars = carMapper.selectByCondition(query);

        // 转换为DTO并处理租赁信息
        return cars.stream()
                .map(this::enrichCarWithRentalInfo)
                .collect(Collectors.toList());
    }

    @Override
    public CarDTO addCar(CarDTO carDTO) {
        Car car = convertToCar(carDTO);
        car.setStatus("1"); // 默认状态为可租用
        car.setRentalCount(0); // 设置初始值为0
        carMapper.insert(car);
        return convertToCarDTO(car);
    }

    @Override
    public CarDTO updateCar(CarDTO carDTO) {
        Car car = convertToCar(carDTO);
        carMapper.updateById(car);
        return convertToCarDTO(car);
    }

    @Override
    public void deleteCar(Long id) {
        carMapper.deleteById(id);
    }

    @Override
    public boolean rentCar(Long carId, Long userId, Date rentalStart, Date rentalEnd) {
        // 检查车辆状态是否可租 - 使用常量代替硬编码
        Car car = carMapper.selectById(carId);
        if (car == null || !"1".equals(car.getStatus())) {
            return false;
        }

        // 创建租赁记录
        RentalRecordDTO rentalDTO = new RentalRecordDTO();
        rentalDTO.setCarId(carId);
        rentalDTO.setUserId(userId);
        rentalDTO.setRentalStart(rentalStart);

        rentalDTO.setRentalEnd(rentalEnd);
        rentalDTO.setStatus("1"); // 使用常量
        CarWithUserDTO carWithUserDTO = new CarWithUserDTO(null,carId, userId, rentalStart, rentalEnd, 1);
        System.out.println("carWithUserDTO:"+carWithUserDTO);
        int i = carWithUserClient.addCarWithUser(carWithUserDTO);
        try {
            boolean rentalCreated = rentalClient.addRental(rentalDTO);
            if (!rentalCreated) {
                return false;
            }
            // 更新车辆状态
            car.setStatus("0");
            carMapper.updateByIds(car);

            return true;
        } catch (Exception e) {
            System.out.println("Failed to create rental record: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean returnCar(Long CarId) {
        try {
            // 1. 验证车辆是否存在
            Car car = carMapper.selectById(CarId);
            if (car == null) {
                throw new RuntimeException("车辆不存在");
            }

            // 2. 查询关联的租赁记录
            RentalRecordDTO rental = rentalClient.QueryByCarId2(CarId);
            System.out.println("rental:"+rental);

            // 3. 更新租赁记录状态为"已归还"
            boolean rentalUpdated = rentalClient.updateRentalStatus(rental.getRentalId());

            if (!rentalUpdated) {
                throw new RuntimeException("更新租赁记录状态失败");
            }

            // 4. 更新车辆状态为"可用"
            car.setStatus("1");
            carMapper.updateByIds(car);
            carWithUserClient.deleteCarWithUser(CarId);
            return true;
        } catch (Exception e) {
            System.out.println("还车过程中发生异常，carId={}"+ CarId+e);
            throw e; // 重新抛出异常以便控制器处理
        }

    }
    private CarDTO enrichCarWithRentalInfo(Car car) {
        CarDTO dto = convertToCarDTO(car);

        // 如果是已租用状态，获取租赁信息
        if (rentedStatus.equals(car.getStatus())) {
            RentalDTO rental = rentalClient.QueryByCarId(car.getId());
            if (rental != null) {
                User user = userClient.getUserWithId(rental.getUserId());
                dto.setUser(user);
                Rental rental1 = convertToEntity(rental);
                dto.setRental(rental1);
            }
        }

        return dto;
    }



    public Car convertToCar(CarDTO dto) {
        Car car = new Car();
        car.setId(dto.getId());
        car.setLicensePlate(dto.getLicensePlate());
        car.setModel(dto.getModel());
        car.setStatus(dto.getStatus());
        car.setPricePerDay(dto.getPricePerDay());
        car.setProductionYear(dto.getProductionYear());
        car.setManufacturer(dto.getManufacturer());
        car.setRentalCount(dto.getRentalCount());
        return car;
    }

    public CarDTO convertToCarDTO(Car car) {
        CarDTO dto = new CarDTO();
        dto.setId(car.getId());
        dto.setLicensePlate(car.getLicensePlate());
        dto.setManufacturer(car.getManufacturer());
        dto.setModel(car.getModel());
        dto.setStatus(car.getStatus());
        dto.setPricePerDay(car.getPricePerDay());
        dto.setProductionYear(car.getProductionYear());
        dto.setRentalCount(car.getRentalCount());
        return dto;
    }

    public Rental convertToEntity(RentalDTO dto) {
        if (dto == null) {
            return null;
        }
        Rental rentalRecord = new Rental();
        rentalRecord.setId(dto.getId());
        rentalRecord.setCarId(dto.getCarId());
        rentalRecord.setUserId(dto.getUserId());
        rentalRecord.setRentalStart(dto.getRentalStart());
        rentalRecord.setRentalEnd(dto.getRentalEnd());
        return rentalRecord;
    }

    public RentalRecord convertToEntity(RentalRecordDTO dto) {
        if (dto == null) {
            return null;
        }
        RentalRecord rentalRecord = new RentalRecord();
        rentalRecord.setRentalId(dto.getRentalId());
        rentalRecord.setCarId(dto.getCarId());
        rentalRecord.setUserId(dto.getUserId());
        rentalRecord.setRentalStart(dto.getRentalStart());
        rentalRecord.setRentalEnd(dto.getRentalEnd());
        rentalRecord.setStatus(dto.getStatus());
        rentalRecord.setRentalCount(dto.getRentalCount());
        return rentalRecord;
    }
}
